package com.yige.web.controller

import com.mongodb.BasicDBObject
import com.mongodb.DBObject
import com.yige.common.DateUtil
import com.yige.common.NumUtil
import com.yige.common.ResultUtil
import com.yige.common.SystemConstant
import com.yige.common.ToDBObjectUtil
import com.yige.service.mongoService.MongoGoodsClassService
import com.yige.service.mongoService.MongoGoodsGroupService
import com.yige.service.mongoService.MongoGoodsNumService
import com.yige.service.mongoService.MongoGoodsService
import com.yige.service.mongoService.MongoStorageGoodsService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseBody

import java.awt.font.NumericShaper

/**
 * Created by sunhao on 2015/10/9 0009.
 */

@Controller
@RequestMapping("goods")
class GoodsController {

    @Autowired
    MongoGoodsService goodsService
    @Autowired
    MongoGoodsClassService goodsClassService
    @Autowired
    MongoGoodsGroupService goodsGroupService
    @Autowired
    MongoStorageGoodsService storageGoodsService
    @Autowired
    MongoGoodsNumService goodsNumService



    /*****************控制器模块*****************/


    /**
     * 显示商品类别列表
     * @param model
     * @return
     */
    @RequestMapping("classList.do")
    def classList(Model model){
        goodsClassArgs(model)
        goodsGroupArgs(model)
        return "goods/classList"
    }

    /**
     * 添加商品类别
     * @param name
     * @param price
     * @param cost
     * @param count
     * @return
     */
    @RequestMapping("addGoodsClass")
    @ResponseBody
    def add(String name, Double price, String group){
        def goods_group = goodsGroupService.findOneById(group)
        def goods_classList = goodsClassService.findListByQuery([group:goods_group.name_cn]as BasicDBObject)
        def list = new ArrayList()
        def int num = 0
        if(goods_classList.size() == 0){
            num = NumUtil.createNumByGoodsClass(group)
            //累计商品类型编号
        }else {
            goods_classList.each {info->
                list.add(info.num)
            }
            int max = list.max()
            num = NumUtil.createNumByGoodsClass(max)
            //累计商品类型编号
        }
        Map<String,Object> goodsInfo = [_id:UUID.randomUUID().toString(),name:name,price:price,storage_date:new Date(),count:0,group:goods_group.name_cn,num:num]
        DBObject dbObject = ToDBObjectUtil.toDBObject(goodsInfo)
        boolean flag = goodsClassService.insertOne(dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 删除商品类别
     * @param _ids
     * @return
     */
    @RequestMapping("delGoodsClass")
    @ResponseBody
    def del(@RequestParam('_ids') List<String> _ids){
        boolean flag = false
        _ids.each {_id->
            flag = goodsClassService.deleteOne(_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 修改商品类别
     * @param _id
     * @param name
     * @param price
     * @param cost
     * @param count
     * @return
     */
    @RequestMapping("updateGoodsClass")
    @ResponseBody
    def update(String _id, String name, Double price,Integer count, String group){
        def goods = goodsGroupService.findOneById(group)
        Map<String,Object> goodsInfo = [_id:_id,name:name,price:price,count:count,group:goods.name_cn]//!!!!!!!!!!!!!!!!!!!!!
        DBObject dbObject = ToDBObjectUtil.toDBObject(goodsInfo)
        boolean flag = goodsClassService.updateOne(_id,dbObject)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 显示商品列表
     * @param model
     * @return
     */
    @RequestMapping("list.do")
    def list(Model model){
        List<DBObject> goodsList = goodsService.findList()
        goodsArgs(model, goodsList)
        return "goods/list"
    }

    /**
     * 多条件联合查询商品列表
     * @param model
     * @param name
     * @param storage_startDate
     * @param storage_endDate
     * @param delivery_startDate
     * @param delivery_endDate
     * @return
     */
    @RequestMapping("find")
    def find(Model model,String name, String storage_startDate,String storage_endDate, String delivery_startDate, String delivery_endDate, String status){
        def query = new BasicDBObject()
        def goodsList
        if(!StringUtils.isEmpty(name)){
            query.append("name",~/${name}/)
        }
        if(!StringUtils.isEmpty(storage_startDate) && !StringUtils.isEmpty(storage_endDate)){
            query.append("storage_date",[$gte:DateUtil.parseDate(storage_startDate), $lte:DateUtil.parseDate(storage_endDate)]as BasicDBObject)
        }
        if(!StringUtils.isEmpty(delivery_startDate) && !StringUtils.isEmpty(delivery_endDate)){
            query.append("delivery_date",[$gte:DateUtil.parseDate(delivery_startDate), $lte:DateUtil.parseDate(delivery_endDate)]as BasicDBObject)
        }
        if(!StringUtils.isEmpty(status)){
            if(status.equals("in")){
                goodsList = goodsService.notSoldGoods()
            }else {
                goodsList = goodsService.soldGoods()
            }
        }else {
            goodsList = goodsService.findListByQuery(query)
        }
        goodsArgs(model,goodsList)
        return "goods/list"
    }

    /**
     * 入库管理
     * @param model
     * @return
     */
    @RequestMapping("storage.do")
    def storageGoodsList(Model model){
        List<DBObject> goodsList = storageGoodsService.findList()
        storageGoodsArgs(model,goodsList)
        goodsClassArgs(model)
        return "goods/storageGoods"
    }


    /**
     * 添加入库商品
     * @param name
     * @param cost
     * @param storage_date
     * @param info
     */
    @RequestMapping("storageGoods")
    @ResponseBody
    def storageGoods(String nameId, Double cost, String storage_date, String info){
        DBObject goods = goodsClassService.findOneById(nameId)
        def goodInfo = [_id: UUID.randomUUID().toString(),name: goods.name, cost: cost, storage_date: DateUtil.parseDate(storage_date), info: info]as BasicDBObject
        boolean flag = addGoods(goodInfo,nameId)
        ResultUtil.recallAjax(flag)
    }

    /**
     * 删除入库商品
     * @param _ids
     * @return
     */
    @RequestMapping("delStorageGoods")
    @ResponseBody
    def delStorageGoods(@RequestParam(value = "_ids") List<String> _ids){
        boolean flag = false
        def goods = []as BasicDBObject,goodsClass = []as BasicDBObject
        _ids.each {_id->
            goods = storageGoodsService.findOneById(_id)
            goodsClass = goodsClassService.findOneByQuery([name:goods.name]as BasicDBObject)
            flag = storageGoodsService.deleteOne(_id)
            goodsClassService.reduceCountForGoods(goodsClass._id, 1)
            goodsService.deleteOne(_id)
        }
        ResultUtil.recallAjax(flag)
    }

    /**
     * 显示商品详细信息
     * @param goodsId
     * @param model
     * @return
     */
    @RequestMapping("info")
    def goodsInfo(@RequestParam("goodsId") String goodsId, Model model){
        def goods_db = goodsService.findOneById(goodsId)
        def list = new ArrayList()
        list.add(goods_db)
        goodsArgs(model,list)
        return "goods/info"
    }



    /*****************方法模块*****************/

    /**
     * 向商品列表添加商品
     * @param dbObject
     */
    def addGoods(DBObject dbObject, String nameId){
        String name = dbObject.get("name"),str = "",str_sub
        DBObject goodsClass = goodsClassService.findOneByQuery([name:name]as BasicDBObject)
        def goodsList = goodsService.findListByQuery([name:name]as BasicDBObject)
        def list = new ArrayList()
        String num
        if(goodsList.size() == 0){
            num = NumUtil.createNumByGoodsNew(goodsClass.num)
        }else {
            goodsList.each {info->
                str = info.get("num")
                str_sub = str.substring(str.length()-3,str.length())
                list.add(Integer.parseInt(1 + str_sub))
            }
            int max = list.max()
            num = str.substring(0,7) + NumUtil.createNumByGoods(Integer.toString(max)).substring(1)
            //累计商品类型编号
        }
        dbObject.put("num",num)
        double price = goodsClassService.findOneById(goodsClass._id).price, pay = 0
        Date delivery_date = null
        def goodInfo = [_id: dbObject._id,
                        num: num,
                        name: dbObject.name,
                        cost: dbObject.cost,
                        price: price,
                        pay: pay,
                        storage_date:dbObject.storage_date,
                        delivery_date:delivery_date,
                        info: dbObject.info]as BasicDBObject
        boolean flag = false
        storageGoodsService.insertOne(dbObject)
        goodsClassService.createCountForGoods(nameId, 1)
        flag = goodsService.insertOne(goodInfo)
        return flag
    }

    /**
     * 商品类型参数
     * @param model
     * @return
     */
    def goodsClassArgs(Model model){
        def goodsClassList = goodsClassService.findList() as ArrayList
        model.addAttribute("goodsClasses",goodsClassList)
    }

    /**
     * 商品种类参数
     * @param model
     * @return
     */
    def goodsGroupArgs(Model model){
        def groupList = goodsGroupService.findList() as ArrayList
        model.addAttribute("groups",groupList)
    }

    /**
     * 商品列表参数
     * @param model
     * @param goodsInfo
     * @return
     */
    def goodsArgs(Model model,List goodsInfo){
        def goodsMap = new HashMap()
        def list = new ArrayList()
        def deliverDate, pay, pay0
        goodsInfo.each {
            goodsMap.put("_id",it._id)
            goodsMap.put("num",it.num)
            goodsMap.put("name",it.name)
            goodsMap.put("cost",it.cost)
            goodsMap.put("price",it.price)
            pay = it.pay
            if(pay == 0){
                pay0 = "未售出"
                goodsMap.put("pay",pay0)
            } else if(pay < 0){
                pay0 = "未付款"
                goodsMap.put("pay",pay0)
            } else {
                goodsMap.put("pay",pay)
            }
            goodsMap.put("storageDate",DateUtil.formatDate(it.storage_date))
            if(it.delivery_date == null){
                deliverDate = "未出库"
            }else {
                deliverDate = DateUtil.formatDate(it.delivery_date)
            }
            goodsMap.put("deliveryDate",deliverDate)
            list.add(goodsMap)
            goodsMap = new HashMap()
        }
        if(goodsInfo.size() == 1){
            model.addAttribute("goods",list.get(0))
        }else {
            model.addAttribute("goods",list)
        }
    }

    /**
     * 入库商品参数
     * @param model
     * @param goodsInfo
     * @return
     */
    def storageGoodsArgs(Model model,List goodsInfo){
        def goodsMap = new HashMap()
        def list = new ArrayList()
        goodsInfo.each {
            goodsMap.put("_id",it._id)
            goodsMap.put("name",it.name)
            goodsMap.put("cost",it.cost)
            goodsMap.put("num",it.num)
            goodsMap.put("storageDate",DateUtil.formatDate(it.storage_date))
            list.add(goodsMap)
            goodsMap = new HashMap()
        }
        model.addAttribute("goods",list)
    }

}
